/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eu.fsiebert.polytech.db.mediatheque.front.servlet;

import eu.fsiebert.polytech.db.mediatheque.entity.Adherent;
import eu.fsiebert.polytech.db.mediatheque.entity.CommandeDuJour;
import eu.fsiebert.polytech.db.mediatheque.entity.Item;
import eu.fsiebert.polytech.db.mediatheque.session.AdherentFacade;
import eu.fsiebert.polytech.db.mediatheque.session.CommandeDuJourFacade;
import eu.fsiebert.polytech.db.mediatheque.session.ItemFacade;
import java.util.List;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author hocine
 */
@WebServlet(name = "Panier", urlPatterns = {"/Panier"})
public class Panier extends HttpServlet {

    @EJB
    private CommandeDuJourFacade facade;  
    @EJB
    private ItemFacade itemFacade;  
    @EJB
    private AdherentFacade adherentFacade;  
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        
        String action         = (String) request.getParameter("action");
        
        if(action != null){
            if(action.equals("addToCart")){
                this.addToCard(request, response);
            }
            else if(action.equals("removeFromCard")){
                this.removeFromCard(request, response);
            }
            else if(action.equals("validateCard")){
                this.validateCard(request, response);
            }
            
            String redirect = request.getParameter("redirect");
            if(redirect == null) redirect = "index.jsp";
            request.getRequestDispatcher(redirect).forward(request, response);
        }else{
            request.getRequestDispatcher("pages/panier.jsp").forward(request, response);
        }

        
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void addToCard(HttpServletRequest request, HttpServletResponse response) {
         HttpSession session = request.getSession();
         Integer ref = Integer.parseInt(request.getParameter("item"));
         List<Item> panier = (List<Item>)session.getAttribute("panier");
         panier.add(itemFacade.find(ref));
         session.setAttribute("panier", panier);
    }
    
    private void removeFromCard(HttpServletRequest request, HttpServletResponse response) {
         HttpSession session = request.getSession();
         Integer ref = Integer.parseInt(request.getParameter("item"));
         List<Item> panier = (List<Item>)session.getAttribute("panier");
         panier.remove(itemFacade.find(ref));
         session.setAttribute("panier", panier);
    }
    
    private void validateCard(HttpServletRequest request, HttpServletResponse response) {
        try {
            
            HttpSession session = request.getSession();
            List<Item> panier = (List<Item>)session.getAttribute("panier");
            Adherent user = (Adherent)session.getAttribute("user");
            CommandeDuJour commande = new CommandeDuJour();
            commande.setDate(new Date());
            commande.setItemList(panier);
            commande.setNoCarte(user);
            System.out.println(commande.toString());
            List<CommandeDuJour> commandes = new ArrayList<CommandeDuJour>();
            commandes.add(commande);
            user.setCommandeDuJourList(commandes);
            
            adherentFacade.merge(user);
            panier.clear();
            session.setAttribute("panier", panier);
            session.setAttribute("user", user);
            
            Properties		props	    = new Properties();
            props.setProperty("mail.from", "contact@mediatheque.fr");
            Message message = new MimeMessage(Session.getInstance(props));
            InternetAddress	recipient = new InternetAddress(user.getLogin());

            message.setRecipient(Message.RecipientType.TO, recipient);
            message.setSubject("Validation de votre commande");
            message.setText("Bonjour,\n"
                    + "Votre commande a bien été enregistrée.\n"
                    + "Vous recevrez très prochainement la confirmation du gestionnaire et vous pourrez alors venir chercher votre commande.");

            Transport.send(message);
            
        }catch (AddressException ex) {
            Logger.getLogger(Panier.class.getName()).log(Level.SEVERE, null, ex);
        }catch (MessagingException ex) {
            Logger.getLogger(Panier.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void reserveItem(HttpServletRequest request, HttpServletResponse response) {
        
        
    }
    
}
